<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <el-form
          ref="userForm"
          label-width="120px"
          style="margin-left: 120px; margin-top: 30px"
          :model="userInfo"
          :rules="rules"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userInfo.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userInfo.mobile" style="width: 300px" disabled />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="userInfo.timeOfEntry"
              type="date"
              class="inputW"
            />
          </el-form-item>
          <el-form-item label="员工头像">
            <img-upload ref="imgUpload" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="bthOk">更新</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getUserIconApi } from '@/api/user'
import { editEmployeesApi } from '@/api/employees'
export default {
  name: 'EmployeesDetail',
  data() {
    return {
      userInfo: {
        timeOfEntry: '', // 入职时间
        username: '', // 姓名
        mobile: '', // 手机
        staffPhoto: ''// 头像
      },
      // 校验规则
      rules: {
        username: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 获取动态路由传过来的ID
    userId() {
      return this.$route.params.id
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 修改
    async bthOk() {
      try {
        await this.$refs.userForm.validate()
      } catch (error) {
        return console.log(error)
      }
      // this.$refs.imgUpload.fileList[0]?.url  问号表示判断前面是不是为空，如果是问号后面的不会执行
      const imgUpload = this.$refs.imgUpload
      // 取到数组中的URL赋值给userinfo中的staffPhoto
      const url = imgUpload.fileList[0]?.url
      // 判断图片是否正在上传中，如果是允许提交
      if (!url) {
        this.$message.success('图片未上传')
      }
      if (!imgUpload.isAllUploadSuccess) {
        this.$message.warning('图片正在上传中')
        return
      }
      this.userInfo.staffPhoto = url
      await editEmployeesApi(this.userInfo)
      this.$message.success('更新成功')
      this.$router.go(0)
    },
    // 数据回显
    async getUserInfo() {
      const res = await getUserIconApi(this.userId)
      console.log(res)
      this.userInfo = res.data
      this.$refs.imgUpload.fileList = [{ url: res.data.staffPhoto }]
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
